var util = require('../../utils/util');

var that;
var deltaX = 0;
var mincomputedValue;
// 1.5 总刻度值
var maxcomputedValue;

var app = getApp();

const date = new Date()
const years = []
const months = []
const days = []
for (let i = 1930; i <= date.getFullYear(); i++) {
  years.push(i)
}
for (let i = 1; i <= 12; i++) {
  months.push(i)
}
for (let i = 1; i <= 31; i++) {
  days.push(i)
}
const year = date.getFullYear();
const month = date.getMonth() + 1;
const day = date.getDay() + 1;

const aimsOptional = [];
for (let i = 1; i <= 22; i++) {
  aimsOptional.push(i);
}
Page({
  data: {
    // 日期所用數據
    years, months, days,
    year, month, day,
    birthvalue: [year, month - 1, day - 1],
    // 性别
    icurl: '../../images/sex.png',
    icboy: '../../images/sex-boy.png',
    icgirl: '../../images/sex-girl.png',
    selectSex: '1',
    // 身高
    imgurl: '../../images/ic-height.png',
    peric: '../../images/people.png',
    ruler: '../../images/hrule.png',
    heightList: [],
    canvasHeight: 80,
    computedValue: 80,
    // base
    pageNum: 0,
    isComplete:false,
    title: "",
    answerOption: [],
    questionContext: "",
    type: 0,
    date: new Date(),
    isNumber:"",
    // 选中选项
    selectVal: "",
    selectid: '',
    // 跑步目标
    aimsValue: 5,
    aimsOptional,
    // 默认禁用下一步按钮
    isDisabled: true,
    // 多选题
    mutableValAnswer: {},
    mutableIdAnswer: {},
    // 输入框文字
    inputVal: "",
    backgroundImg:""
  },

  onLoad() {
    Object.prototype.values=function(obj){
const arr = [];
for(let key in obj){
  arr.push(obj[key]);
}
return arr;
    };
    const question = wx.getStorageSync('questionItem');
    question && this.setData({
      title: question.title,
      answerOption: question.choose,
      questionContext: question,
      pageNum: +question.id,
      type: +question.type,
      // 如果等于1 则默认禁用按钮
      isDisabled: +question.required === 1,
      isNumber: question.isNumber,
      backgroundImg: this.getBackgroundImg(+question.id)
    });
    // 防止reflow
    setTimeout(_ => this.setData({ isComplete: true}),250);
    this.initCanvasPage(question);

  },


  // 答案函数
  //下一步按钮提交答案
  nextStep(e) {
    const typeCount = this.data.type;
    // 默认为空即下一步进入到下一页 但是如果是选择题则会有值进行转跳
    let optionalid = '';

    let value = "";
    switch (+typeCount) {
      case 0:
        value = this.data.selectVal;
        optionalid = this.data.selectid;
        break;
      case 1:
        value = this.data.inputVal;
        break;
      case 2:
        value = `${this.data.year}-${this.data.month}-${this.data.day}`;
        break;
      case 3:
        value = this.data.computedValue;
        break;
      case 4:
        value = this.data.computedValue;
        break;
      case 5:
        value = +this.data.selectSex === 1 ? '男' : '女';
        break;
      case 6:
        value = `${this.data.aimsValue}公里/周`;
        break;
      case 7:
        value = Object.values(this.data.mutableValAnswer).join(",");
        optionalid = Object.values(this.data.mutableIdAnswer);
        break;
      default:
        break;
    }


    // null即不轉跳
    this.submitHandler(value, optionalid);
  },
  //填空按钮提交答案
  commitAnswer(e) {
    const optionalvalue = e.currentTarget.dataset.optionalvalue;
    const optionalid = e.currentTarget.dataset.optionalid;
    this.submitHandler(optionalvalue, optionalid);
  },
  //提交處理进入下一个问题
  submitHandler(optionalvalue, optionalid) {
    const questionContext = this.data.questionContext;
    const answerData = {
      title: questionContext.title,
      questionId: questionContext.id,
      type: questionContext.type,
      value: optionalvalue || '无',
      
    };
    if (optionalid != null && !Array.isArray(optionalid)){
      answerData.optional = optionalid;
    }
    util.commitAnswer(answerData, res => console.log(res));
    
    if (questionContext.end){
// 如果是最后一题
      util.sendRequest("WXUpdateQuestionState",{isOk:1},res=>{
        wx.setStorageSync("userInfo", { ...wx.getStorageSync("userInfo"), isOverQuestion:1});
        // 不需要跳到loading页面了
        // wx.redirectTo({
        //   url: './loading',
        // })
        util.wxModalAlert({ content: "教练马上努力给您做计划，2-3天之后给您计划哟，别着急" },_ => wx.redirectTo({
          url: '/pages/personal/perplan2',
        }));
        
      },"正在上传");
     } 
    else {
      let conditionItem = '';
      if (Array.isArray(optionalid)) {

        optionalid.forEach(id => {
          // 多选题
          const item = questionContext.condition.filter(
            item => +item.optional === +id)[0];
          item ? conditionItem = item : void (0);
        });
      } else {
        conditionItem = questionContext.condition.filter(item => +item.optional === +optionalid)[0];
      }

      const redirectPageNum = conditionItem ? conditionItem.redirectTo : -1;
      const pageNum = redirectPageNum === -1 ? this.data.pageNum : redirectPageNum - 1;

      util.getQuestion(pageNum, res => {
        const data = res.result;
        wx.setStorageSync('questionItem', data);
        wx.reLaunch({
          url: './question',
        });
        // 正式版
        // wx.redirectTo({
        //   url: './question',
        // })
      });
    }
  },

getBackgroundImg(num){
            let url = "";
            switch (num){
             case 11:
                url ="../../images/腰围测试.png";
                break;
             case 33:
                url = "../../images/柔韧性测试.png";
               break; 
               case 34:
                url = "../../images/俯卧撑.png";
               break; 
               case 36:
                url = "../../images/仰卧撑.png";
               break;
            }
  return `background-image:url(${url})`
},

  // 事件函数
  // 输入文字
  inputAnswer(e) {
    this.setData({
      inputVal: e.detail.value,
      isDisabled: !e.detail.value
    })
  },
  // 添加选择项(多选框)
  addAnswerItem(e) {

    const optionalvalue = e.currentTarget.dataset.optionalvalue || e.detail.value;
    const optionalid = e.currentTarget.dataset.optionalid;
    const key = e.currentTarget.dataset.key;
    const isActive = !!this.data.mutableValAnswer[key];

    // 如果已经选择了则赋值空
    this.setData({
      mutableIdAnswer: {
        ...this.data.mutableIdAnswer,
        [key]: isActive ? '' : optionalid
      }
    });
    this.setData({
      mutableValAnswer: {
        ...this.data.mutableValAnswer,
        [key]: isActive ? '' : optionalvalue
      }
    });
    const isEmpty = !Object.values(this.data.mutableValAnswer).filter(item => item).length;
    this.setData({
      isDisabled: isEmpty
    });
  },
  // 切换生日函数
  changeBrithday(e) {
    const val = e.detail.value;
    this.setData({
      year: this.data.years[val[0]],
      month: this.data.months[val[1]],
      day: this.data.days[val[2]],
      isDisabled: false
    })
  },
  // 切换选项
  selectChange(e) {
    const val = e.detail.value[0];
    const item = this.data.answerOption[val];

    this.setData({
      selectVal: item.value,
      selectid: item.optional,
      isDisabled: false
    });
  },
  selectAimsChange(e) {
    const val = e.detail.value[0] + 1;

    this.setData({
      aimsValue: val,
      isDisabled: false
    });
  },
  // 更换图片
  selectMale: function () {
    this.setData({ icgirl: '../../images/sex-girl.png', icboy: '../../images/sex-boy-h.png', selectSex: '1', isDisabled: false });
    wx.setStorageSync('selectSex', 1);
  },
  selectFeMale: function () {
    this.setData({ icboy: '../../images/sex-boy.png', icgirl: '../../images/sex-girl-h.png', selectSex: '2', isDisabled: false });
    wx.setStorageSync('selectSex', 2);
  },



  // 初始化有画布的页面
  initCanvasPage(question) {
    // 如果是身高页面 则初始化身高画布
    if (+question.type === 3 || +question.type === 4) {
      if (+question.type === 3) {
        mincomputedValue = 80;
        maxcomputedValue = 250;
      } else {
        // 体重页面
        mincomputedValue = 30;
        maxcomputedValue = 150;
        this.setData({
          imgurl: '../../images/ic-weight.png',
          peric: '../../images/people.png',
          ruler: '../../images/ruler.png',
          canvasHeight: 80,
          computedValue: 30,
        });
      }

      that = this;
      var sex = wx.getStorageSync('selectSex');
      if (sex == 1) {
        that.setData({ peric: '../../images/nanpeople.jpg' })
      }
      // 绘制标尺
      that.drawRuler();
      // 绘制三角形游标
      that.drawCursor();
    }

  },
  // 初始化画布
  drawRuler: function () {

    /* 1.定义变量 */

    // 1.1 定义原点与终点，x轴方向起点与终点各留半屏空白
    var origion = { x: app.screenWidth / 2, y: that.data.canvasHeight };
    var end = { x: app.screenWidth / 2, y: that.data.canvasHeight };
    // 1.2 定义刻度线高度
    var heightDecimal = 50;
    var heightDigit = 25;
    // 1.3 定义文本标签字体大小
    var fontSize = 20;
    // 1.4 最小刻度值
    // 已经定义在全局，便于bindscroll访问

    // 1.6 当前刻度值
    var currentcomputedValue = that.data.computedValue;
    // 1.7 每个刻度所占位的px
    var ratio = 10;
    // 1.8 画布宽度
    var canvasWidth = maxcomputedValue * ratio + app.screenWidth - mincomputedValue * ratio;

    // 设定scroll-view初始偏移
    that.setData({
      canvasWidth: canvasWidth,
      scrollLeft: (currentcomputedValue - mincomputedValue) * ratio
    });

    /* 2.绘制 */

    // 2.1初始化context
    const context = wx.createCanvasContext('canvas-ruler');
    // 遍历maxcomputedValue
    for (var i = 0; i <= maxcomputedValue; i++) {
      context.beginPath();
      // 2.2 画刻度线
      context.moveTo(origion.x + (i - mincomputedValue) * ratio, origion.y);
      // 画线到刻度高度，10的位数就加高
      context.lineTo(origion.x + (i - mincomputedValue) * ratio, origion.y - (i % ratio == 0 ? heightDecimal : heightDigit));
      // 设置属性
      context.setLineWidth(2);
      // 10的位数就加深
      context.setStrokeStyle(i % ratio == 0 ? 'gray' : 'darkgray');
      // 描线
      context.stroke();
      // 2.3 描绘文本标签
      context.setFillStyle('gray');
      if (i % ratio == 0) {
        context.setFontSize(fontSize);
        // 为零补一个空格，让它看起来2位数，页面更整齐
        context.fillText(i == 0 ? ' ' + i : i, origion.x + (i - mincomputedValue) * ratio - fontSize / 2, fontSize);
      }
      context.closePath();
    }

    // 2.4 绘制到context
    context.draw();

  },
  drawCursor: function () {
    /* 定义变量 */
    // 定义三角形顶点 TODO x
    var center = { x: app.screenWidth / 2, y: 5 };
    // 定义三角形边长
    var length = 20;
    // 左端点
    var left = { x: center.x - length / 2, y: center.y + length / 2 * Math.sqrt(3) };
    // 右端点
    var right = { x: center.x + length / 2, y: center.y + length / 2 * Math.sqrt(3) };
    // 初始化context
    const context = wx.createCanvasContext('canvas-cursor');
    context.moveTo(center.x, center.y);
    context.lineTo(left.x, left.y);
    context.lineTo(right.x, right.y);
    // fill()填充而不是stroke()描边，于是省去手动回归原点，context.lineTo(center.x, center.y);
    context.setFillStyle('#48c23d');
    context.fill();
    context.draw();
  },
  bindscroll: function (e) {

    // deltaX 水平位置偏移位，每次滑动一次触发一次，所以需要记录从第一次触发滑动起，一共滑动了多少距离
    deltaX += e.detail.deltaX;
    var computedValue = (- deltaX / 10 + mincomputedValue).toFixed(1)
    if (computedValue < 0.01) {
      computedValue = 0;
    } else if (computedValue >= maxcomputedValue) {
      computedValue = maxcomputedValue;
    }

    // 数据绑定
    that.setData({
      computedValue: computedValue,
      isDisabled: false
    });
    // console.log(deltaX)

  },




})